package com.qf.zk;

import com.qf.util.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

import java.io.IOException;

/**
 * ZK操作
 * @author zjw
 */
public class ZookeeperTest {

    @Test
    public void create() throws Exception {
        // 获取连接
        CuratorFramework client = ZkClient.getClient();
        // 创建ZNode
        client.create().withMode(CreateMode.PERSISTENT).forPath("/zk","嘿嘿嘿".getBytes());
        // 释放资源
        client.close();
    }


    @Test
    public void delete() throws Exception {
        // 获取连接
        CuratorFramework client = ZkClient.getClient();
        // 删除ZNode
        client.delete().deletingChildrenIfNeeded().forPath("/xxx");
        // 释放资源
        client.close();
    }

    @Test
    public void listen() throws IOException {
        // 获取连接
        CuratorFramework client = ZkClient.getClient();
        // 构建监听对象
        CuratorCache curatorCache = CuratorCache.builder(client,"/zk").build();
        // 监听回调
        curatorCache.listenable().addListener(new CuratorCacheListener() {
            @Override
            public void event(Type type, ChildData oldData, ChildData data) {
                System.out.println("以下分别为Type，OldData，NewData");
                System.out.println(type.name());
                System.out.println(new String(oldData.getData()));
                System.out.println(new String(data.getData()));
            }
        });
        // 开启监听
        curatorCache.start();


        System.in.read();

    }

}
